﻿using System.Linq;
using System.Web.Mvc;
using TelerikConnect.Models;
using TelerikConnect.Web.DBConnect;

namespace TelerikConnect.Web.Controllers
{
    public class RecommendController : Controller
    {
        private readonly TelerikDb db = new TelerikDb();

        [Authorize]
        public ActionResult Recommend(int id)
        {
            if (!db.Recommendations.Any(r => r.Skill.Id == id && r.Voter.UserName == User.Identity.Name))
            {
                db.Recommendations.Add(new RecommendationModel
                {
                    Skill = db.Skills.First(s => s.Id == id),
                    Voter = db.UserProfiles.FirstOrDefault(x => x.UserName == User.Identity.Name)
                });

                db.SaveChanges();
            }

            return Json(new { }, JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        public ActionResult UnRecommend(int id)
        {
            if (db.Recommendations.Any(r => r.Skill.Id == id && r.Voter.UserName == User.Identity.Name))
            {
                db.Recommendations.Remove(db.Recommendations.Single(r => r.Skill.Id == id && r.Voter.UserName == User.Identity.Name));
                db.SaveChanges();

                return new EmptyResult();
            }

            return new EmptyResult();
        }

        public ActionResult Recommenders(int id)
        {
            return Json(new
            {
                recommenders = db.Recommendations.Where(r => r.Skill.Id == id).Select(
                    r => r.Voter.UserName)
            }, JsonRequestBehavior.AllowGet);
        }
    }
}